package com.sixth.oa.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Calendar;
import java.util.Random;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sixth.oa.entity.model.sixthImg;
import com.sixth.oa.util.ResultStr;

@Controller
@RequestMapping("/file")
public class FileController {
	
	private String url = "http://152.136.136.209:8080/file/";
	private String localUrl = "/file/";
	
	
	/**
	 * 文件上传
	 * @param file
	 * @return
	 */
	@PostMapping("/upload")
	@ResponseBody
	public ResultStr upload(@RequestParam("file") MultipartFile file) {
		sixthImg img = new sixthImg();
		try {
	        byte[] bytes = file.getBytes();
	        String newName = getRedomName()+getpostfix(file.getOriginalFilename());
	        System.out.println(url+newName);
	        File f = new File(localUrl+newName);
	        Path path = f.toPath();
	        Files.write(path, bytes);
	        img.setFileName(newName);
	        img.setOldName(file.getOriginalFilename());
	        img.setImgUrl(url + newName);
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
		return new ResultStr(200,"success",img);
	}
	
	/**
	 * 产生随机名
	 * @return
	 */
	public String getRedomName() {
		String RandomFilename = ""; 
		Random rand = new Random();
		int random = rand.nextInt(); 
		Calendar calCurrent = Calendar.getInstance(); 
		int intDay = calCurrent.get(Calendar.DATE); 
		int intMonth = calCurrent.get(Calendar.MONTH) + 1; 
		int intYear = calCurrent.get(Calendar.YEAR); 
		String now = String.valueOf(intYear) + "_" + String.valueOf(intMonth) + "_" + 
		String.valueOf(intDay) + "_"; 
		RandomFilename = now + String.valueOf(random > 0 ? random : ( -1) * random); 
		return RandomFilename; 
	}
	
	/**
	 * 获取后缀
	 * @param fname
	 * @return
	 */
	public String getpostfix (String fname){
		String postfix=null;
		if (fname==null)
		return "";
		if(fname.indexOf(".")!=-1){
		   postfix=fname.substring(fname.indexOf("."));
		}else{
		  return "非法文件名";
		}
		return postfix;
		}
	

}
